package com.sduept.nwld.dataserver.controller.statistics;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.nwld.dataserver.manager.statistics.CheckPlanMaintenanceManager;
import com.sduept.nwld.dataserver.model.countanalyse.CheckPlan;

@Named
@ViewScoped
public class CheckPlanMaintenanceController extends AbstractController {

	private static final long serialVersionUID = 2308805100553212355L;
	@Autowired
	private CommonDocumentProperties pros;
	@Autowired
	private CheckPlanMaintenanceManager checkPlanManager;

	private List<CheckPlan> checkPlans = new ArrayList<>();
	private CheckPlan selectCheckPlan = new CheckPlan();
	private CheckPlan checkPlan = new CheckPlan();
	
	private List<Integer> years = new ArrayList<>();
	private String year;
	private List<Integer> months = new ArrayList<>();
	private String month;
	private String subCompany;
	private List<String> subCompanys = new ArrayList<String>();

	private StreamedContent templateFile;

	@PostConstruct
	private void init() {
		initYearsAndSubcompany();
		getCurrentYearAndMonth();
		for (int i = 1; i <= 12; i++) {
			months.add(i);
		}
	}
	
	public void getCurrentYearAndMonth() {
		Calendar cal = Calendar.getInstance();
		//Integer currentYear = cal.get(Calendar.YEAR);
		Integer currentMonth = cal.get(Calendar.MONTH )+1;
		//year = currentYear.toString();
		month = currentMonth.toString();
	}
	
	public void initYearsAndSubcompany() {
		years = checkPlanManager.getYears();
		subCompanys = checkPlanManager.getSubCompany();
	}
	
	public void preCreateCheckPlan() {
		checkPlan = new CheckPlan();
	}

	public void editCheckPlan() {
		checkPlan = selectCheckPlan;
	}
	
	public void saveCheckPlan() {
		if (checkPlan != null) {
			if (checkPlan.getId() == null) {// 新建
				if(isNotExist(checkPlan)) {
					getSumWhenCreate(checkPlan);
					CheckPlan act = checkPlanManager.create(checkPlan);
					checkPlans.add(act);
				} else {
					addErrorMessage("该信息已存在，添加失败！");
					return;
				}
			} else {// 编辑
				getSumWhenEdit(checkPlan);
				checkPlanManager.create(checkPlan);
				selectCheckPlan = new CheckPlan();
			}
			addSuccessMessage("保存成功!");
		}
		initYearsAndSubcompany();
		queryByCondition();
	}
	/**
	 * 如果不存在，返回false
	 * 如果存在，返回true
	 * @param checkPlan
	 * @return
	 */
	private boolean isNotExist(CheckPlan checkPlan) {
		boolean flag = false;
		int y = checkPlan.getYear();
		String company = checkPlan.getSubCompany();
		int m = checkPlan.getMonth();
		List<CheckPlan> chps = checkPlanManager.query(y+"", m+"", company);
		if(chps.size() == 0) {
			//当前记录不存在
			flag = true;
		}
		return flag;
	}
	
	/**
	 * 新建一条记录，修改该年份的全年总值，
	 * 如果全年总值记录存在,将新添加的记录的plan_value和finish_value的值加入month=0中
	 * 如果不存在,将新添加的记录值即为month=0的值
	 */
	public void getSumWhenCreate(CheckPlan checkPlan) {
		String company = checkPlan.getSubCompany();
		int checkyear = checkPlan.getYear();
		Float plan = checkPlan.getPlan();
		Float reality = checkPlan.getReality();
		CheckPlan monthCheckPlan = new CheckPlan();
		List<CheckPlan> monthCheckPlans = checkPlanManager.query(checkyear+"", "0", company);
		if(monthCheckPlans.size() != 0) {
			//已经存在month=0的记录，将当前checkPlan的plan和reality加入month=0的记录
			monthCheckPlan = monthCheckPlans.get(0);
			monthCheckPlan.setPlan(plan + monthCheckPlan.getPlan());
			monthCheckPlan.setReality(reality + monthCheckPlan.getReality());
		} else {
			//不存在month=0的记录，则当前checkPlan的值就是month=0的值
			monthCheckPlan.setMonth(0);
			monthCheckPlan.setMonthText("全年总值");
			monthCheckPlan.setPlan(plan);
			monthCheckPlan.setReality(reality);
			monthCheckPlan.setSubCompany(company);
			monthCheckPlan.setYear(checkyear);
			checkPlans.add(monthCheckPlan);
		}
		checkPlanManager.create(monthCheckPlan);
	}

	/**
	 * 编辑一条记录，修改该年份的全年总值
	 * 将原纪录与新纪录的差值加入全年总值
	 */
	public void getSumWhenEdit(CheckPlan checkPlan) {
		List<CheckPlan> oldCheckPlans = checkPlanManager.getCheckPlanById(checkPlan.getId());
		CheckPlan oldCheckPlan = oldCheckPlans.get(0);
		String company = oldCheckPlan.getSubCompany();
		int y = oldCheckPlan.getYear();
		float addPlan = checkPlan.getPlan() - oldCheckPlan.getPlan();
		float addReality = checkPlan.getReality() - oldCheckPlan.getReality();
		List<CheckPlan> monthCheckPlans = checkPlanManager.query(y+"", "0", company);
		CheckPlan monthCheckPlan = monthCheckPlans.get(0);
		monthCheckPlan.setPlan(addPlan + monthCheckPlan.getPlan());
		monthCheckPlan.setReality(addReality + monthCheckPlan.getReality());
		checkPlanManager.create(monthCheckPlan);
	}
	
	public void deleteCheckPlan() {
		if (selectCheckPlan != null && !selectCheckPlan.getId().isEmpty()) {
			checkPlanManager.deleteCheckPlanById(selectCheckPlan.getId());
			//修改当年总值
			deleteSum(selectCheckPlan);
			addSuccessMessage("删除成功!");
			initYearsAndSubcompany();
			selectCheckPlan = new CheckPlan();
		} else {
			addErrorMessage("请选择要删除的数据!");
		}
		queryByCondition();
	}
	
	/**
	 * 如果没有当年1至12月份的数据，删除month=0的记录
	 * 如果有1至12月份的数据，修改month=0的记录
	 * @param selectCheckPlan
	 */
	public void deleteSum(CheckPlan checkPlan) {
		int y = checkPlan.getYear();
		String company = checkPlan.getSubCompany();
		Float plan = checkPlan.getPlan();
		Float reality = checkPlan.getReality();
		List<CheckPlan> sumCheckPlans = checkPlanManager.query(y+"", "0", company);
		CheckPlan sumCheckPlan = sumCheckPlans.get(0);
		
		List<CheckPlan> exitCheckPlans = checkPlanManager.getCheckPlansMonthIsNotEquals0(y, company);
		if(exitCheckPlans.size() !=0) {
			sumCheckPlan.setPlan(sumCheckPlan.getPlan()-plan);
			sumCheckPlan.setReality(sumCheckPlan.getReality()-reality);
			checkPlanManager.create(sumCheckPlan);
		} else {
			checkPlanManager.deleteCheckPlanById(sumCheckPlan.getId());
		}
	}

	public void queryByCondition() {
		checkPlans = checkPlanManager.query(year, month, subCompany);
	}
	
	public void initCondition() {
		Calendar cal = Calendar.getInstance();
		Integer currentYear = cal.get(Calendar.YEAR);
		Integer currentMonth = cal.get(Calendar.MONTH )+1;
		if(years.contains(currentYear)) {
			year = currentYear.toString();
		} else {
			year = "0";
		}
		month = currentMonth.toString();
		subCompany = "全部";
		queryByCondition();
	}
	
	/**
	 * 文件下载
	 */
	public void fileDownloadView() {        
		InputStream stream = null;
		try {
//			stream = new FileInputStream(new File(pros.getTempletePath()+"checkPlan.xlsx"));
			stream = new FileInputStream(new File(pros.getTempletePath()+"checkPlan.xlsx"));
			templateFile = new DefaultStreamedContent(stream, "xlsx", "checkPlan.xlsx");
		} catch (FileNotFoundException e) {
			addErrorMessage("下载文件失败，请联系技术人员！");
			e.printStackTrace();
		}
    }
	
	public void chooseEquipment() {
        Map<String,Object> options = new HashMap<String, Object>();
        options.put("resizable", true);
        options.put("draggable", true);
        options.put("modal", true);
        options.put("width", 600);
        options.put("height", 200);
        
        Map<String,List<String>> params = new HashMap<>();
        List<String> param = new ArrayList<>();
        param.add("1");	//设置去除前几行
        params.put("ingnoreRows", param);
        openDialog("/ui/common/upload_excel_define", params, options);
    }

	public void onSelectorChosen(SelectEvent event) {
		List<List<String>>objs = (List<List<String>>) event.getObject();
		List<Integer> errorList = new ArrayList<Integer>();
		int i = 0;
		try {
			for (List<String> list : objs) {
				i++;
				//subCompany;plan;reality;month;year;name
				CheckPlan checkPlan = new CheckPlan();
				int month = NumberFormat.getInstance().parse(list.get(3).toString()).intValue();
				int year =NumberFormat.getInstance().parse(list.get(4).toString()).intValue();
				if(month > 0 && month < 13) {
					checkPlan.setSubCompany((String) list.get(0));
					checkPlan.setPlan(Float.valueOf((String) list.get(1)));
					checkPlan.setReality(Float.valueOf((String) list.get(2)));
					checkPlan.setMonth(month);
					checkPlan.setYear(year);
					checkPlan.setName((String) list.get(5));
					createOrUpdateCheckPlan(checkPlan);
				}else {
					errorList.add(i);
					continue;
				}
			}
			addSuccessMessage("文件上传成功！");
			initYearsAndSubcompany();
			initCondition();
		}catch(Exception e) {
			e.printStackTrace();
			addErrorMessage("表格数字有误，请仔细核对！");
			return ;
		}
		if(errorList.size() != 0) {
			String errorRecord = "";
			for(int j = 0; j<errorList.size(); j++) {
				errorRecord += errorList.get(j) + " ";
			}
			addErrorMessage("文件第"+errorRecord+"行有误，上传失败");
		}
		queryByCondition();
	}
	
	public void createOrUpdateCheckPlan(CheckPlan checkPlan) {
		checkPlans = checkPlanManager.getAllCheckPlans();
		int y = checkPlan.getYear();
		String company = checkPlan.getSubCompany();
		int m = checkPlan.getMonth();
		List<CheckPlan> chps = checkPlanManager.query(y+"", m+"", company);
		if(chps.size() == 0) {
			//当前记录不存在
			getSumWhenCreate(checkPlan);
			checkPlanManager.create(checkPlan);
		} else {
			editSumWhenUploadFile(checkPlan,chps);
			CheckPlan cp = chps.get(0);
			cp.setPlan(checkPlan.getPlan());
			cp.setReality(checkPlan.getReality());
			cp.setName(checkPlan.getName());
			checkPlans.set(checkPlans.indexOf(cp), cp);
			checkPlanManager.create(cp);
		}		
	}
	
	public void editSumWhenUploadFile(CheckPlan checkPlan,List<CheckPlan> chps) {
		CheckPlan oldCheckPlan = chps.get(0);
		float addPlan = checkPlan.getPlan() - oldCheckPlan.getPlan();
		float addReality = checkPlan.getReality() - oldCheckPlan.getReality();
		List<CheckPlan> monthCheckPlans = checkPlanManager.query(checkPlan.getYear()+"", "0", checkPlan.getSubCompany());
		CheckPlan monthCheckPlan = monthCheckPlans.get(0);
		monthCheckPlan.setPlan(addPlan + monthCheckPlan.getPlan());
		monthCheckPlan.setReality(addReality + monthCheckPlan.getReality());
		checkPlanManager.create(monthCheckPlan);
	}
	
	public void onRowSelect(SelectEvent event) {
		selectCheckPlan = (CheckPlan) event.getObject();
	}
	
	public void selectYear() {
		FacesContext con = FacesContext.getCurrentInstance();
		Map<String,String> map = con.getExternalContext().getRequestParameterMap();
		year = map.get("year").toString();
	}
	
	public List<String> completeSubCompany(String query) {
        return subCompanys;
    }
	public List<CheckPlan> getCheckPlans() {
		return checkPlans;
	}

	public void setCheckPlans(List<CheckPlan> checkPlans) {
		this.checkPlans = checkPlans;
	}

	public CheckPlan getSelectCheckPlan() {
		return selectCheckPlan;
	}

	public void setSelectCheckPlan(CheckPlan selectCheckPlan) {
		this.selectCheckPlan = selectCheckPlan;
	}

	public CheckPlan getCheckPlan() {
		return checkPlan;
	}

	public void setCheckPlan(CheckPlan checkPlan) {
		this.checkPlan = checkPlan;
	}

	public String getSubCompany() {
		return subCompany;
	}

	public void setSubCompany(String subCompany) {
		this.subCompany = subCompany;
	}

	public List<String> getSubCompanys() {
		return subCompanys;
	}

	public void setSubCompanys(List<String> subCompanys) {
		this.subCompanys = subCompanys;
	}

	public List<Integer> getYears() {
		return years;
	}

	public void setYears(List<Integer> years) {
		this.years = years;
	}

	public List<Integer> getMonths() {
		return months;
	}

	public void setMonths(List<Integer> months) {
		this.months = months;
	}

	public StreamedContent getTemplateFile() {
		return templateFile;
	}

	public void setTemplateFile(StreamedContent templateFile) {
		this.templateFile = templateFile;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public String getMonth() {
		return month;
	}

	public void setMonth(String month) {
		this.month = month;
	}
	
}
